import subprocess
import os
import sys

try:
    # 获取当前脚本所在目录
    base_dir = os.path.dirname(os.path.abspath(__file__))
    manage_py = os.path.join(base_dir, "mysite", "manage.py")

    # 检查manage.py是否存在
    if not os.path.exists(manage_py):
        print(f"错误: 找不到manage.py文件 {manage_py}")
        sys.exit(1)

    print(f"正在启动Django服务器...")
    print(f"Manage.py路径: {manage_py}")

    # 使用当前Python解释器而不是指定虚拟环境中的Python
    work_dir = os.path.join(base_dir, "mysite")

    # 使用sys.executable获取当前Python解释器路径，并指定端口为8000
    result = subprocess.run(
        [sys.executable, "manage.py", "runserver", "8000"],  # 明确指定端口号
        cwd=work_dir,
    )

    print(f"服务器已停止，退出码: {result.returncode}")

except KeyboardInterrupt:
    print("\n程序被用户中断")
except Exception as e:
    print(f"发生错误: {e}")
